package com.modules.config.integration.authenticator;

import cn.hutool.core.util.StrUtil;
import com.common.bean.execption.UnloginException;
import com.common.constant.SecurityConstants;
import com.common.enums.AuthTypeEnum;
import com.modules.config.integration.base.AbstractPreparableIntegrationAuthenticator;
import com.modules.config.integration.base.IntegrationAuthentication;
import com.modules.upms.entity.vo.AuthUserVO;
import com.modules.upms.entity.SysUser;
import com.modules.upms.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 默认登录处理
 *
 * @author LIQIU
 * @date 2018-3-31
 **/
@Component
@Primary
public class UsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public AuthUserVO authenticate(IntegrationAuthentication integrationAuthentication) {
        SysUser sysUser = sysUserService.findUserByLoginName(integrationAuthentication.getUsername());

        if (sysUser == null) {
            throw new UnloginException("用户名不存在或者密码错误");
        }

        return new AuthUserVO(sysUser);
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {

    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StrUtil.isBlank(integrationAuthentication.getAuthType()) ||
                StrUtil.equals(integrationAuthentication.getAuthType(), AuthTypeEnum.WEB.getCode());
    }
}
